package com.ruoyi.project.im.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IpToAddressUtil;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenrateUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.im.avatar.domain.VisitorAvatar;
import com.ruoyi.project.im.avatar.service.IVisitorAvatarService;
import com.ruoyi.project.im.bean.IMAuth;
import com.ruoyi.project.im.bean.IMBaseRes;
import com.ruoyi.project.im.code.domain.Code;
import com.ruoyi.project.im.code.service.ICodeService;
import com.ruoyi.project.im.friends.domain.Friends;
import com.ruoyi.project.im.friends.service.IFriendsService;
import com.ruoyi.project.im.groups.domain.Groups;
import com.ruoyi.project.im.groups.service.IGroupsService;
import com.ruoyi.project.im.kuaijie.domain.Kuaijie;
import com.ruoyi.project.im.kuaijie.service.IKuaijieService;
import com.ruoyi.project.im.lixian.domain.Lixian;
import com.ruoyi.project.im.lixian.service.ILixianService;
import com.ruoyi.project.im.members.domain.GroupMembers;
import com.ruoyi.project.im.members.service.IGroupMembersService;
import com.ruoyi.project.im.personhost.domain.Personhost;
import com.ruoyi.project.im.personhost.service.IPersonhostService;
import com.ruoyi.project.im.statistics.domain.Statistics;
import com.ruoyi.project.im.statistics.service.StaticsService;
import com.ruoyi.project.im.userip.domain.UserIpLimits;
import com.ruoyi.project.im.userip.service.UserIpLimitsService;
import com.ruoyi.project.im.users.domain.Register;
import com.ruoyi.project.im.users.domain.Users;
import com.ruoyi.project.im.users.service.IUsersService;
import com.ruoyi.project.im.utils.*;
import com.ruoyi.project.im.wechatlist.domain.Wechatlist;
import com.ruoyi.project.im.wechatlist.service.IWechatlistService;
import com.ruoyi.project.im.welcome.domain.Welcome;
import com.ruoyi.project.im.welcome.service.IWelcomeService;
import com.ruoyi.project.monitor.server.domain.Sys;
import com.ruoyi.project.system.jilu.domain.KamiJilu;
import com.ruoyi.project.system.jilu.service.IKamiJiluService;
import com.ruoyi.project.system.user.domain.User;
import org.aspectj.weaver.loadtime.Aj;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import org.jsoup.Jsoup;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class ApiController extends BaseController {

    @Autowired
    private IUsersService usersService;
    @Autowired
    private IWelcomeService welcomeService;
    @Autowired
    private IKuaijieService kuaijieService;
    @Autowired
    private IGroupMembersService groupMembersService;
    @Autowired
    private StaticsService staticsService;
    @Autowired
    private IPersonhostService iPersonhostService;
    @Autowired
    private UserIpLimitsService userIpLimitsService;
    @Autowired
    private IWechatlistService iWechatlistService;



    @Autowired
    private ILixianService iLixianService;

    @Autowired
    private IGroupsService groupsService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IVisitorAvatarService avatarService;

    @Autowired
    private IFriendsService friendsService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IKamiJiluService kamiJiluService;
    @GetMapping("/test")
    public AjaxResult testGetIP(String value, HttpServletRequest request){

        String ipAddr = Http.getIpAddr(request);
        return AjaxResult.success(ipAddr);
    }

    @GetMapping("/ipLocation")
    public AjaxResult ipLocation(HttpServletRequest request){
        String ipAddr = Http.getIpAddr(request);
        Map<String,Object> map = new HashMap<>();
        map.put("ip",ipAddr);
        map.put("city",getIpInfo(ipAddr));
        return AjaxResult.success(map);
    }

    /**
     * 客服登录
     */
    @GetMapping("/customer/login")
    public AjaxResult login(String password,HttpServletRequest request){

        if (StringUtils.isEmpty(password)){
            return AjaxResult.error("卡密不能为空");
        }

        Code code = codeService.selectCodeBycodeResult(password);

        if (code == null){
            return AjaxResult.error("卡密有误");
        }
        String ip = Http.getIpAddr(request);
        Users byusers= code.getUsers();
        if(null == byusers){
            return AjaxResult.error("卡密有误");
        }
        //卡密查到绑定用户未激活需要激活
        if (byusers.getActStatus()==0){
            if("sold".equals(code.getIssold())&&"nouse".equals(code.getKamistatus())){  //卡密已售出 并且未使用才能注册
                long date=new Date().getTime();
                if("uselogin".equals(code.getKamitype())){
                    date+=code.getDays() * 24 * 60 * 60 * 1000;
                }else if("useceshi".equals(code.getKamitype())){
                    date+=2 * 60 * 60 * 1000;
                }else {
                    return AjaxResult.error("该卡密不是登陆卡密!");
                }
                Date endTime=new Date(date);
                byusers.setEndTime(endTime);
                byusers.setActStatus(1);
                int row = usersService.updateUsers(byusers);
                KamiJilu kmju=new KamiJilu();  //添加卡密使用记录
                kmju.setBeforeTime(new Date());
                kmju.setAfterTime(endTime);
                kmju.setUseTime(new Date());
                kmju.setKamitype("uselogin");
                kmju.setUsekami(password);
                kmju.setUseId(byusers.getCreateUser());
                kamiJiluService.insertKamiJilu(kmju);
                if (row > 0){
                    code.setUsetime(new Date());
                    code.setUserId(byusers.getUserId());
                    code.setKamistatus("inuse");
                    code.setBeizhu(byusers.getUserId());
                    codeService.updateCode(code);
                    usersService.updateUsersByOpration(byusers);//增加域名和群
                }
            }else{
                return AjaxResult.error("请联系客服,激活该卡密!");
            }

         }
            long nowDay = new Date().getTime();
            long useDay = byusers.getEndTime().getTime();
            if(useDay < nowDay){
                return AjaxResult.error("卡密已过期");
            }
//            Users users = usersService.selectUsersByUserId(code.getUserId());

            if (byusers.getStatus() != 1){
                return AjaxResult.error("账号已冻结");
            }

            IMBaseRes baseRes = getUserToken(byusers.getUserId());
            if (baseRes.errCode != 0){
                return AjaxResult.error("登入失败");
            }
            updateUserIP(byusers.getUserId(),ip);
            return AjaxResult.success(baseRes);

    }

    /**
     * 游客登录
     * 如果
     */
    @PostMapping("/user/visitorLogin")
    public AjaxResult visitorLogin(@RequestBody Register register,HttpServletRequest request){
        //根据 code去找客服对应信息
        Personhost personhost = iPersonhostService.selectPersonhostByShortcode(register.shortCode);
        if (personhost == null){
            return AjaxResult.error("参数有误");
        }
        if (register.getUserId() == null){
            return AjaxResult.error("参数有误");
        }
        String kefuid= personhost.getUserId(); //通过code获得userId
        String groupId=personhost.getGroupId();  //如果没有群id 证明是 客服码进入 不需要邀请进入任何群
        String ip = Http.getIpAddr(request);
        Users user = usersService.selectUsersByUserId(register.getUserId()); //缓存传过来的或者前端传过来的ID
        if(user == null){  // 如果为空,用ip加客服id查询
            Users user1 = new Users();
            user1.setKefuId(kefuid);
            user1.setLastLoginIp(ip);
            user = usersService.selectUsersByKefuIdWithIP(user1);
        }
        if(user != null){ //用户有缓存 并登入过
            boolean flag=userIpLimitsService.getUserIpLimitByUserId(user.getUserId(), kefuid,ip);
            if(flag){
                return AjaxResult.error("黑名单");
            }
            addFriend(user.getUserId(),kefuid);
            addGroup(groupId,user.getUserId(),user.getName());
            IMBaseRes imBaseRes = getUserToken(user.getUserId());
            updateUserIP(user.getUserId(),ip);
            return AjaxResult.success(imBaseRes);
        }else { //新注册 本地缓存 和 数据都没有
            VisitorAvatar visitorAvatar = getAvatar();
            if (visitorAvatar == null){
                return AjaxResult.error("内部出错");
            }
            String nickname= visitorAvatar.getName();
            String userId =  register.getUserId();
            String avatar = visitorAvatar.getAvatar();
            AjaxResult ajaxResult = registerUser(userId,nickname,avatar,kefuid,ip,false);
            addFriend(register.getUserId(),kefuid);
            addGroup(groupId,userId,nickname);
            return ajaxResult;
        }
    }

    private VisitorAvatar getAvatar(){
        VisitorAvatar visitorAvatar = avatarService.selectVisitorAvatarById(0L);
        if(visitorAvatar != null){
            visitorAvatar.setuCount(visitorAvatar.getuCount()+1);
            avatarService.updateVisitorAvatar(visitorAvatar);
            return visitorAvatar;
        }
        return null;
    }

    /**
     * 获取落地域名
     */
    @GetMapping("/domain/getDomain")
    public AjaxResult getDomain(Integer type,String code){
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("code错误");
        }
        Personhost personhost=new Personhost();
        if(type==1){
            personhost= iPersonhostService.selectPersonhostByCodeAndType(code);
        }else if(type==2){
            personhost= iPersonhostService.selectPersonhostByUrl(code);
        }
        if(null==personhost){
            return AjaxResult.error("非法访问");
        }
        String userID=personhost.getUserId();
        Personhost luodi=iPersonhostService.selectPersonhostByLuodi(userID);
        Map<String,Object> map=new HashMap<>();
        map.put("userId",personhost.getUserId());
        map.put("groupId",personhost.getGroupId());
        map.put("code",personhost.getShortcode());
        if(luodi != null){
            map.put("url",luodi.getUrl());
            return AjaxResult.success(map);
        }
        return AjaxResult.error();
    }

    @GetMapping("/domain/getGroupCode")
    public AjaxResult getGroupCode(String groupId){
        Personhost personhost= iPersonhostService.selectPersonhostByGroupId(groupId);
        if(personhost != null){
            return AjaxResult.success(personhost);
        }
        return AjaxResult.error();
    }

    @GetMapping("/resetPassword")
    public AjaxResult resetPassword(String userId,String newPwd,String oldPwd){
       Users users= usersService.selectUsersByUserId(userId);
       if(null==users||!users.getPassword().equals(oldPwd)){
          return AjaxResult.error("旧密码不正确");
       }
       users.setPassword(newPwd);
       return usersService.updateUsers(users)==1?AjaxResult.success("修改成功"):AjaxResult.error("修改失败");
    }


    /**
     * 拉黑
     */
    @GetMapping("/user/black")
    public  AjaxResult black(UserIpLimits userIpLimits){
        return  toAjax(userIpLimitsService.insertUserIpLimit(userIpLimits));
    }

    /**
     * 获取当前用户的群组
     */
    @GetMapping("/chat/group")
    public AjaxResult getGroup(String userId){
        Groups groups = groupsService.selectGroupsByUserId(userId);
        return AjaxResult.success(groups);
    }



    /**
     * 获取客服的欢迎语
     */
    @GetMapping("/message/getWelcome")
    public TableDataInfo getWelCome(String userId){
        startPage();
        Welcome welcome = new Welcome();
        welcome.setUserId(userId);
        List<Welcome> list = welcomeService.selectWelcomeList(welcome);
        return getDataTable(list);
    }

    /**
     * 添加客服的欢迎语
     */
    @GetMapping("/message/addWelcome")
    public AjaxResult addWelcome(Welcome welcome){
        return toAjax(welcomeService.insertWelcome(welcome));
    }

    @GetMapping("/message/deletedWelcome")
    public AjaxResult deletedWelcome(Integer id){
        return toAjax(welcomeService.deleteWelcomeById(id));
    }


    @GetMapping("/message/updateDefWelcome")
    public AjaxResult updateDefWelcome(Welcome welcome){
        return toAjax(welcomeService.updateWelcomeById(welcome));
    }


    @GetMapping("/fast/list")
    public TableDataInfo getFastList(Kuaijie kuaijie) {
        startPage();
        List<Kuaijie> list = kuaijieService.selectKuaijieList(kuaijie);
        return getDataTable(list);
    }

    @GetMapping("/fast/add")
    public AjaxResult addFast(Kuaijie kuaijie) {
        return toAjax(kuaijieService.insertKuaijie(kuaijie));
    }

    @GetMapping("/fast/deleted")
    public AjaxResult deletedFast(Long id){
        return toAjax(kuaijieService.deleteKuaijieById(id));
    }

    @GetMapping("/fast/update")
    public AjaxResult updateFast(Kuaijie kuaijie){
        return toAjax(kuaijieService.updateKuaijie(kuaijie));
    }


    @GetMapping("/offline/list")
    public TableDataInfo getOfflineList(Lixian lixian) {
        startPage();
        List<Lixian> list = iLixianService.selectLixianList(lixian);
        return getDataTable(list);
    }

    @GetMapping("/offline/add")
    public AjaxResult addOffline(Lixian lixian) {
        return toAjax(iLixianService.insertLixian(lixian));
    }

    @GetMapping("/offline/deleted")
    public AjaxResult deletedOffline(Long id){
        return toAjax(iLixianService.deleteLixianById(id));
    }

    @GetMapping("/offline/update")
    public AjaxResult updateOffline(Lixian lixian){
        return toAjax(iLixianService.updateLixian(lixian));
    }


    /**
     * 访问统计
     */
    @GetMapping("/statistics/search")
    public AjaxResult search(String userId){
        Map<String,Object> map=new HashMap<>();
        //今日新增
        Statistics today=staticsService.getTodayByUserId(userId);

        //今日活跃
        Statistics todayActive=staticsService.getTodayByUserId(userId);

        //获得所有
        Statistics allMember=staticsService.getAllByUserId(userId);
        //30天统计
        List<Statistics> day30= staticsService.get30DayByUserId(userId);
        map.put("today",today);
        map.put("todayActive",todayActive);
        map.put("day30",day30);
        map.put("allMember",allMember);
        return AjaxResult.success(map);
    }

    /**
     * 线路列表
     */
    @GetMapping("/domain/getLine")
    public AjaxResult getLine(String userId){
        List<Personhost> personhosts = iPersonhostService.getLine(userId);
        return AjaxResult.success(personhosts);
    }



    /**
     * 更新用户code
     */
    @GetMapping("/domain/updateCode")
    public AjaxResult updateKfCode(Long id){
        String code=UUIDGenrateUtil.generateShortUuid();
        Personhost personhost = iPersonhostService.selectPersonhostById(id);
        personhost.setShortcode(code);
        if (iPersonhostService.updatePersonhost(personhost) == 1){
            return AjaxResult.success(personhost);
        }else {
            return AjaxResult.error("更新失败");
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/user/getUserInfo")
    public AjaxResult getUserInfo(String userId){
        Users users = usersService.selectUsersByUserId(userId);
        if(users != null){
            return AjaxResult.success(users);
        }
        return AjaxResult.error();
    }

    @GetMapping("/group/getGroupMemberList")
    public AjaxResult getGroupMemberList(String groupID){
        GroupMembers groupMembers = new GroupMembers();
        groupMembers.setGroupID(groupID);
        return AjaxResult.success(groupMembersService.selectGroupMembersList(groupMembers));
    }

    @GetMapping("/user/usercode")
    public AjaxResult usercode(String groupID){
        String kefuid= iPersonhostService.selectPersonhostByShortcode(groupID).getUserId();

        return AjaxResult.success(kefuid);
    }

    @GetMapping("/qrcode")
    public void qrcode(String content, HttpServletResponse response){
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(content, "/home/www/logo.png", os);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/chat/joinGroup")
    public AjaxResult joinGroup(GroupMembers members){

        if(members == null){
            return AjaxResult.error();
        }
        if (members.getUserID() == null){
            return AjaxResult.error("用户ID不能为空");
        }

        if (members.getGroupID() == null){
            return AjaxResult.error("群ID不能为空");
        }


        GroupMembers members1 =  groupMembersService.selectGroupByMembers(members);

        if (members1 != null){
            return AjaxResult.success();
        }
        List<String> users = new ArrayList<>();
        users.add(members.getUserID());
        Map<String,Object> map = new HashMap<>();
        map.put("reason","");
        map.put("invitedUserIDList",users);
        map.put("groupID",members.getGroupID());
        map.put("operationID",IMManager.getOperationID());
        map.put("secret", IMManager.secret);
        String jsonString = JSON.toJSONString(map);
        JSONObject result = Http.post(Http.Join_Group_URL,jsonString);
        if (result.getIntValue("errCode") == 0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }

    }

    public void addFriend(String userId,String kefuId){

        Friends fParmas = new Friends();
        fParmas.setOwnerUserId(kefuId);
        fParmas.setFriendUserId(userId);
        Friends friends = friendsService.selectOneFriend(fParmas);
        if(friends == null){
            Map<String,Object> map = new HashMap<>();
            map.put("fromUserID",userId);
            map.put("toUserID",kefuId);
            map.put("reqMsg","");
            map.put("operationID",IMManager.getOperationID());
            map.put("secret", IMManager.secret);
            String jsonString = JSON.toJSONString(map);
            JSONObject result = Http.post(Http.ADD_FRIEND,jsonString);
            if (result.getIntValue("errCode") == 0){
                Map<String,Object> agree = new HashMap<>();
                agree.put("flag",1);
                agree.put("fromUserID",kefuId);
                agree.put("handleMsg","ok");
                agree.put("operationID",IMManager.getOperationID());
                agree.put("toUserID",userId);
                jsonString = JSON.toJSONString(agree);
                Http.post(Http.ADD_FRIEND_RESPONSE, jsonString);
            }
        }
    }

    /**
     * 添加用户到群组
     */
    private void addGroup(String groupId,String userId,String nickName){
        if (groupId == null) return;
        GroupMembers members = new GroupMembers();
        members.setGroupID(groupId);
        members.setUserID(userId);
        GroupMembers groupMembers = groupMembersService.selectGroupByMembers(members);
        if(groupMembers == null){  //没有加入群
            List<String> users = new ArrayList<>();
            users.add(userId);
            Map<String,Object> map = new HashMap<>();
            map.put("reason","");
            map.put("invitedUserIDList",users);
            map.put("groupID",groupId);
            map.put("operationID",IMManager.getOperationID());
            map.put("secret", IMManager.secret);
            String jsonString = JSON.toJSONString(map);
            JSONObject result = Http.post(Http.Join_Group_URL,jsonString);
            if (result.getIntValue("errCode") == 0){
                threadPoolTaskExecutor.execute(new SendWelcomeMsg(groupId,nickName));
            }
        }

    }



    /**
     * 群组发送欢迎语
     */
    @GetMapping("/manager/sendMsg")
    public AjaxResult sendWelcomeMessage(String groupId,String nickName){

        Groups groups = groupsService.selectGroupsByGroupId(groupId);
        if(groups != null){
            if(groups.getWelcome() != null && groups.getWelcome().length() > 0){
                String createUserId = groups.getCreatorUserId();
                Users users = usersService.selectUsersByUserId(createUserId);
                if(users != null){
                    String welcome = groups.getWelcome();
                    List<String> list = new ArrayList<>();
                    Map<String,String> content = new HashMap<>();
                    content.put("text","Hi "+nickName + "，"+welcome);
                    Map<String,Object> map = new HashMap<>();
                    map.put("operationID",IMManager.getOperationID());
                    map.put("sendId",users.getUserId());
                    map.put("recvID","");
                    map.put("groupID",groupId);
                    map.put("senderNickname",users.getName());
                    map.put("senderFaceURL",users.getFaceUrl());
                    map.put("senderPlatformID",7);
                    map.put("content",content);
                    map.put("contentType",101);
                    map.put("sessionType",2);
                    map.put("forceList",list);
                    String jsonString = JSON.toJSONString(map);
                    JSONObject result = Http.post(Http.SendWelcomeMessageURL,jsonString);
                    return AjaxResult.success(result);
                }
            }
        }
        return AjaxResult.error();
    }

    @GetMapping("/group/updateGroupWelcome")
    public AjaxResult updateGroupWelcome(String groupId,String welcome){

        Groups groups = groupsService.selectGroupsByGroupId(groupId);
        if (groups == null){
            return AjaxResult.error("群信息有误");
        }
        groups.setWelcome(welcome);
        Groups updateGroup = new Groups();
        updateGroup.setGroupId(groupId);
        updateGroup.setWelcome(welcome);
        return toAjax(groupsService.updateGroups(updateGroup));
    }

    @GetMapping("/group/getGroupInfo")
    public AjaxResult getGroupWelcome(String groupId){
        Groups groups = groupsService.selectGroupsByGroupId(groupId);
        if (groups == null){
            return AjaxResult.error("群信息有误");
        }
        return AjaxResult.success(groups);
    }

    /**
     * 获取用户token
     */
    private IMBaseRes getUserToken(String userId){
        Map<String,Object> map = new HashMap<>();
        map.put("platform",5);
        map.put("userID",userId);
        map.put("operationID",IMManager.getOperationID());
        map.put("secret", IMManager.secret);
        String jsonString = JSON.toJSONString(map);
        JSONObject result = Http.post(Http.USER_TOKEN,jsonString);
        return result.toJavaObject(IMBaseRes.class);
    }

    private void updateUserIP(String userId,String IP){
        Users users = new Users();
        users.setUserId(userId);
        users.setLastLoginIp(IP);
        users.setLastLoginCity(getIpInfo(IP));
        users.setLastLoginTime(new Date());
        usersService.updateUsers(users);
    }



    private AjaxResult registerUser(String userId,String nickname,String avatar,String kefuId,String ip,Boolean isKefe){

        Map<String,Object> map = new HashMap<>();
        map.put("nickname",nickname);
        map.put("faceURL",avatar);
        map.put("platform",5);
        map.put("userID",userId);
        map.put("operationID", IMManager.getOperationID());
        map.put("secret", IMManager.secret);

        String jsonString = JSON.toJSONString(map);
        JSONObject result = Http.post(Http.USER_REGISTER,jsonString);
        IMBaseRes baseRes = result.toJavaObject(IMBaseRes.class);
        JSON json = JSON.parseObject(baseRes.data.toString());
        IMAuth imAuth = json.toJavaObject(IMAuth.class);
        if (!StringUtils.isEmpty(imAuth.token)){
            if (!isKefe){
                Users users = new Users();
                users.setUserId(imAuth.userID);
                users.setLastLoginIp(ip);
                users.setLastLoginCity(getIpInfo(ip));
                users.setLastLoginTime(new Date());
                users.setCreateTime(new Date());
                users.setKefuId(kefuId);
                usersService.updateUsers(users);
            }
            return AjaxResult.success(baseRes);
        }else {
            return AjaxResult.error("登入失败 500");
        }
    }

    private String getIpInfo(String ip) {


        return IpToAddressUtil.getRealAddressByIP(ip);
    }


    class SendWelcomeMsg implements Runnable{

        private String groupId;
        private String nickName;

        public SendWelcomeMsg(String groupId,String nickName){
            this.groupId = groupId;
            this.nickName = nickName;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                sendWelcomeMessage(groupId,nickName);
            }catch (InterruptedException e){

            }
        }
    }




//    /**
//     * 获取公众号
//     */
//    @GetMapping("/wechat/getWechat")
//    public  AjaxResult getWechat(){
//        Wechatlist wechatlist= iWechatlistService.selectWechatlistByInuse();
//        return  AjaxResult.success("ok",wechatlist);
//    }

    //    /**
//     * 微信登录
//     */
//    @GetMapping("/wx/getUserInfo")
//    public AjaxResult getWxUserInfo(String code,String shortCode,HttpServletRequest request){
//
//        Personhost personhost=iPersonhostService.selectPersonhostByShortcode(shortCode);
//        String kefuId=personhost.getUserId();
//
//        if (StringUtils.isEmpty(kefuId)){
//            return AjaxResult.error("没有对应的客服");
//        }
//
//        Users kefu = usersService.selectUsersByUserId(kefuId);
//
//        if (kefu == null){
//            return AjaxResult.error("客服有误");
//        }
//        Wechatlist wechatlist= iWechatlistService.selectWechatlistByInuse();
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wechatlist.getAppId()+"&secret="+wechatlist.getAppSecret()+"&code="+code+"&grant_type=authorization_code";
//        JSONObject result = Http.wxGet(url);
//        WxAuth auth = JSONObject.toJavaObject(result,WxAuth.class);
//        if (auth.errcode != null){
//            return AjaxResult.error("code 已失效");
//        }
//
//        url = "https://api.weixin.qq.com/sns/userinfo?access_token="+auth.access_token+"&openid="+auth.openid+"&lang=zh_CN";
//        JSONObject jsonObject = Http.wxGet(url);
//        WxUserInfo userInfo = JSONObject.toJavaObject(jsonObject,WxUserInfo.class);
//        if (StringUtils.isEmpty(userInfo.openid)){
//            return AjaxResult.error("获取用户信息失败");
//        }
//        String ip =Http.getIpAddr(request);
//        boolean flag=  userIpLimitsService.getUserIpLimitByUserId(userInfo.openid,kefuId,ip);
//        if(flag){
//            return AjaxResult.error("黑名单");
//        }
//        Users users = usersService.selectUsersByUserId(userInfo.openid);
//
//        if (users != null){
//            IMBaseRes imBaseRes = getUserToken(users.getUserId(),request);
//            if (imBaseRes.errCode != 0){
//                return AjaxResult.error("登入失败");
//            }
//            imBaseRes.kefuId=kefuId;
//            return AjaxResult.success(imBaseRes);
//        }else {
////            AjaxResult ajaxResult = registerUser(userInfo.openid,userInfo.nickname,kefuId,userInfo.headimgurl,request);
////            addFriend(userInfo.openid,kefuId);
//            return AjaxResult.error();
//        }
//    }

    @GetMapping("/test1")
    @ResponseBody
    public String test1()
    {
        return IpToAddressUtil.getRealAddressByIP("127.0.0.1");
    }

}
